#!/usr/bin/perl

use strict;
use DBI;
use Time::localtime;
use XML::Simple;

my $CONFIG = XMLin($ENV{'HACKABOT_CFG'});
my $DBCFG = $CONFIG->{'cmdconfig'}->{'database'};

my $client = "/".$CONFIG->{'directory'}."/scripts/client";
my $socket = "/".$CONFIG->{'directory'}."/".$CONFIG->{'socket'};

my $dbhost = $DBCFG->{'host'};
my $dbname = $DBCFG->{'name'};
my $dbuser = $DBCFG->{'user'};
my $dbpass = $DBCFG->{'pass'};

my ($type, $chan, $msg, $nick);
while (<>) {
	if (/^type\s+(\S+)/) {
		$type = $1;
	}
	elsif (/^nick\s*(\S*)/) {
		$nick = $1;
	}
	elsif (/^to\s*(\S*)/) { # We assume there is only one name listed
		$chan = $1;
	}
	elsif (/^msg\s*(.*)/) {
		$msg = $1;
	}
}

if (defined $type) {
	my ($dbh, $sth);

	$dbh = DBI->connect("DBI:mysql:$dbname:$dbhost", $dbuser, $dbpass, { PrintError => 1 });
	if (!$dbh) {
		die "log: Failed to connect to database\n";
	}
	
	my $time = `date "+%F %R"`;
	chomp $time;

	if ($type =~ m/msg/ or $type =~ m/snd/) {
		$type = "msg";
	}
	elsif ($type =~ m/notice/) {
		$type = "notice";
	}
	elsif ($type =~ m/currenttopic/) {
		$type = "topic";
		my $info = `echo 'topicinfo $chan' | $client $socket`;
		chomp $info;
		if ($info =~ /^topicinfo\s+$chan\s+(\S+)\s+(\d+)$/) {
			$nick = $1;
			$time = `date -d '\@$2' '+%F %R'`;
		}
		else {
			$nick = undef;
		}
	}

	if (not ($type eq "msg" or $type eq "action" or $type eq "notice" or
		$type eq "join" or $type eq "part" or $type eq "quit" or
		$type eq "topic" )) {
		die "logger: Unknown type '$type', add it to the enum!\n";
	}

	$time = $dbh->quote($time);
	$type = $dbh->quote($type);
	
	if (defined $nick) {
		$nick = $dbh->quote($nick);
	}
	else {
		$nick = "NULL";
	}
	if (defined $msg) {
		$msg = $dbh->quote($msg);
	}
	else {
		$msg = "NULL";
	}
	if (defined $chan and $chan =~ m/^#/) {
		$chan = $dbh->quote($chan);
	}
	else {
		$chan = "NULL";
	}
	$dbh->do("INSERT log SET date = $time, text = $msg, chan = $chan, nick = $nick, type = $type") or die "log: DB stuff failed.\n";

	$dbh->disconnect;
}
else {
	die "log: All info not found :-/\n";
}
